import React, { useMemo, useState } from "react"
import { Form, Input } from 'antd';

import AbIcon from "@/components/DecorateIcons/Ab_Icon";

/**
 * 验证码类型一
 * @returns 
 */
const VerifyCode = ({ base }) => {
  let {
    label_flag,
    text_flag,
    icon_flag,
    text3,
    icon3
  } = base
  const [codes, setCodes] = useState(getRandCode())

  let codeStr = useMemo(() => {

    // 将验证码拼接成字符串，方便校检比对
    let _codeStr = codes.reduce((pre, next) => {
      return pre + next.num
    }, '')

    return _codeStr.toLowerCase()

  }, [codes])

  let handleClick = () => {
    setCodes(getRandCode())
  }

  // 校检规则
  let rules = [
    () => ({
      validator(_, value) {

        if (!value) {
          return Promise.reject(new Error('请输入验证码'))
        }

        // 比较用户输入的是否正确
        if (value.toLowerCase() === codeStr) {
          return Promise.resolve();
        }

        return Promise.reject(new Error('验证码输入有误'));
      },
    }),
  ]
  return (
    <Form.Item
      name="code"
      required
      rules={rules}
      className='ab-form-item ab-form-item-code'
      label={
        label_flag ?
          <>
            {
              text_flag &&
              <span className='label-text'>{text3}</span>
            }

            {
              icon_flag &&
              <AbIcon iconName={icon3} className='label-icon' />
            }

          </>
          :
          null
      }
    >
      <div className='verify-input-box'>
        <Input className='ab-input-verify' placeholder="请输入验证码" />
        <div className="code-box" onClick={handleClick}>
          {
            codes.map(code => (
              <span
                className="code"
                key={code.key}
                style={code.style}
              >{code.num}</span>
            ))
          }
        </div>
      </div>
    </Form.Item>
  )
}

/**
 * 获取随机验证码
 * @param { number } len 长度 
 */
function getRandCode(len = 4) {
  let output = []

  let chars = [
    "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
    "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
    "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
    "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
    "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
    "3", "4", "5", "6", "7", "8", "9"
  ]
  let colors = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
  let sizes = ['14', '15', '16', '17', '18']


  for (let i = 0; i < len; i++) {
    let item = {
      key: i,
      num: 0,
      style: {
        color: '',
        transform: '',
        fontSize: '',

      }
    }
    // 随机验证码
    let key = Math.floor(Math.random() * chars.length)
    item.num = chars[key]

    // 随机验证码颜色
    let code = '#'
    for (let j = 0; j < 6; j++) {
      let key = Math.floor(Math.random() * colors.length)
      code += colors[key]
    }
    item.style.color = code

    // 随机验证码方向
    let rotate = Math.floor(Math.random() * 60)
    let plus = Math.floor(Math.random() * 2)
    if (plus == 1) rotate = '-' + rotate
    item.style.transform = 'rotate(' + rotate + 'deg)'

    // 随机验证码字体大小
    let size = Math.floor(Math.random() * sizes.length)
    item.style.fontSize = sizes[size] + 'px'

    output.push(item)
  }

  return output
}

export default VerifyCode